package MTG::Shop::NastolkinRu;
use Moose;


use Data::Dumper;
use strict;
use utf8;
use XML::Simple;
use XML::Bare;
use base "MTG";

has 'cards_urls' => ('is' => 'rw', default => sub{ [ ] });
has 'cur_set' => ('is' => 'rw', default => sub { { } });
has 'name_to_id' => ('is' => 'rw', default => sub { { } });
#TMP 
our @prices;
our @names;
our $price_style = "color: #777777; font-weight: bold; text-indent:0px;";
our $name_style = "font-size:13px;";


sub run
{
	my ($self, $dump_source) = @_;
	
	
	foreach my $set (keys %{$self->config->{'sets'}})
	{
		
		$self->cur_set($self->config->{'sets'}->{$set});
		
		if ($self->cur_set->{'dbparse_price'})
		{
			@prices = [];
			@names = [];
			$self->collect_cards_urls($self->cur_set->{'dbparse_price'});	
		}
		
	}
	

}

sub collect_cards_urls
{
	my ($self, $page)  = @_;
	

	foreach my $page_num (1..15)
	{ 	
		$self->www->get($page . $page_num);
		printf("Work With %s\n", $page . $page_num);
		$self->parse_cards_list($self->www->content)
	}
	
	my $hash_ref = $self->dbh->selectall_hashref("select * from cards where card_code_id='" . $self->cur_set->{'code_id'} . "'", "name_rus");
	
	for (my $i = 0; $i < scalar(@prices); $i++)
	{	
		my $name = $names[$i];
		utf8::encode($name);
		my $item = $hash_ref->{$name};
		#create table prices( id INTEGER PRIMARY KEY, last_update int, shop_id int, card_code_id int, card_id int, price int);
		my $sth = $self->dbh->prepare("INSERT INTO prices VALUES (null, ?,?,?,?,?)");
		$sth->execute(time(), 1, $item->{'card_code_id'}, $item->{'card_id'}, $prices[$i]);
	}
}

sub parse_cards_list
{
	my ($self, $content) = @_;
	
	my $count_cards = 0;
	
	$self->clean_tree();
	$self->tree->parse($content);
	$self->tree->normalize_content();
	
	my @ps = $self->tree->find_by_tag_name('p');
	
	foreach my $p (@ps)
	{
		if ($p->attr("style") && $p->attr("style") eq $price_style)
		{
			my $price = $1  if ($p->as_text =~ /(\d+)/);
			push @prices, $price;	
		}
	}
	
	my @as = $self->tree->find_by_tag_name('a');
	
	foreach my $a (@as)
	{
		if ($a->attr("style") && $a->attr("style") eq $name_style)
		{
			my $name = $1  if ($a->as_text =~ /«(.+?)»/);
			push @names, $name;
		}
	}
}

1;
